import React, { useEffect } from 'react'
import { connect } from 'react-redux'
import { Space, Table, Button, Popconfirm, message } from 'antd'
import axios from 'axios'

export const MyTable = ({ list, init, delItem }) => {
    const confirm = (index) => {
        delItem(index)
        message.success('删除成功');
    };

    const cancel = (e) => {
        message.error('取消删除');
    };
    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
        },
        {
            title: '住址',
            dataIndex: 'address',
            key: 'address',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record, index) => (
                <Space size="middle">
                    <Button type="primary">编辑</Button>
                    <Popconfirm
                        title="确定删除么?"
                        onConfirm={() => {
                            confirm(index)
                        }}
                        onCancel={cancel}
                        okText="Yes"
                        cancelText="No"
                    >
                        <Button type="primary" danger>删除</Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    useEffect(() => {
        init()
    }, [])
    return (
        <div>
            <Table columns={columns} dataSource={list} />
        </div>
    )
}


const mapStateToProps = (state) => {
    const { list } = state
    return {
        list
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        init() {
            dispatch((next) => {
                axios.get("/api/getList").then(res => {
                    next({ type: "CHANGE_LIST", list: res.data.list })
                })
            })
        },
        delItem(index) {
            dispatch({ type: "DEL_LIST_ITEM", index })
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyTable)